<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <style>
    body {
      box-sizing: border-box;
      margin: 0;
      cursor: default;
      font-size: 20px;
    }

    *,
    *::before,
    *::after {
      box-sizing: inherit;
    }

    ul {
      list-style-type: none;
      margin-block-start: 0.5em;
      margin-block-end: 0.5em;
    }
    li {
      position: relative;
      margin: 0.5em 0;
      font: normal 1em/1.5em Arial;
      color: #555;
    }

    ul li {
      /* padding-left: 5px; */
    }
  </style>

  <body>
    <div style="display: flex">
      <div
        style="
          height: 50vh;
          width: 60vw;
          border: 2px solid black;
          overflow-y: scroll;
        "
        id="div_left"
      ></div>

      <div
        style="
          height: 50vh;
          width: 40vw;
          border: 2px solid black;
          overflow-y: scroll;
        "
        id="div_right"
      ></div>
    </div>
    <div style="float: right; margin-right: 20px">
      <button onclick="refresh()">刷新</button>
      <button onclick="commit()">提交</button>
    </div>

    <a style="border: 2px solib black">+</a>
  </body>

  <script>
    window.onload = refresh


    /**
     * XMLHttpRequest的Promise封装
     **/
    function XHRPromise(url) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.send();
        let list = null,
          tree = null;
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            let json = JSON.parse(xhr.responseText);
            if (xhr.status === 200) {
              resolve(json);
            } else {
              reject(json);
            }
          }
        };
      });
    }

    function refresh() {
      const request = XHRPromise("http://ext.gaomuxuexi.com:5870/task/random");
      request
        .then((res) => {
          console.log(res);
          list = res.list;
          tree = res.tree;
          appendChildTo(div_left, tree);

          console.log(list);
          for (let el of list) {
            div_right.appendChild(getTreeNode(el.name));
          }
        })
        .catch((err) => {
          alert("请求失败，请查看控制台")
        });
    }

    /**
     * 建造树节点
     **/
    function getTreeNode(text) {
      const newul = document.createElement("ul");
      const newli = document.createElement("li");
      newli.innerHTML = text;
      newul.appendChild(newli);
      return newul;
    }

    /**
     * 递归建树
     **/
    function appendChildTo(node, obj) {
      if (!obj) return;
      const newnode = getTreeNode(obj.N);
      for (let el of obj.C) {
        appendChildTo(newnode, el);
      }
      node.appendChild(newnode);
    }
  </script>
</html>
